# 安装HanLP依赖的PowerShell脚本
# 适用于Windows环境，自动处理Python 3.12兼容性问题
chcp 65001
# 获取Python版本
$pythonVersion = python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
Write-Host "检测到Python版本: $pythonVersion"

# 创建虚拟环境目录
$venvName = "hanlp_env"
if (-not (Test-Path $venvName)) {
    Write-Host "创建虚拟环境: $venvName" -ForegroundColor Green
    python -m venv $venvName
} else {
    Write-Host "虚拟环境已存在: $venvName" -ForegroundColor Yellow
}

# 激活虚拟环境
Write-Host "激活虚拟环境..." -ForegroundColor Green
& ".\$venvName\Scripts\Activate.ps1"

# 安装或升级pip
Write-Host "更新pip..." -ForegroundColor Green
python -m pip install --upgrade pip

# 首先安装setuptools和wheel
Write-Host "安装基础依赖..." -ForegroundColor Green
pip install -U setuptools wheel

# 根据Python版本选择安装方法
if ($pythonVersion -eq "3.12") {
    Write-Host "检测到Python 3.12,使用兼容性安装方法" -ForegroundColor Yellow
    
    # 安装更新版本的numpy
    Write-Host "安装兼容Python 3.12的numpy..." -ForegroundColor Green
    pip install numpy==1.26.0
    
    # 安装PyTorch
    Write-Host "安装PyTorch..." -ForegroundColor Green
    pip install torch
    
    # 安装transformers兼容版本
    Write-Host "安装transformers兼容版本..." -ForegroundColor Green
    pip install transformers==4.29.2
    
    # 安装HanLP
    Write-Host "安装HanLP..." -ForegroundColor Green
    pip install hanlp>=2.1.0b36
    
    # 安装Flask和Werkzeug兼容版本
    Write-Host "安装Flask和相关依赖..." -ForegroundColor Green
    pip install flask==2.3.3 werkzeug==2.3.7
    
    # 安装其他必要依赖
    Write-Host "安装其他必要依赖..." -ForegroundColor Green
    pip install tqdm requests
} else {
    # 对于Python 3.8-3.11，直接从requirements.txt安装
    if (Test-Path "requirements.txt") {
        Write-Host "从requirements.txt安装依赖..." -ForegroundColor Green
        pip install -r requirements.txt
    } else {
        Write-Host "找不到requirements.txt文件,安装默认依赖..." -ForegroundColor Yellow
        pip install numpy==1.22.4 torch==1.13.1 transformers==4.26.1 hanlp==2.1.0b36 flask==2.2.3 werkzeug==2.2.3 tqdm requests
    }
}

# 验证安装
Write-Host "验证安装..." -ForegroundColor Green
python -c "try {
    import numpy
    import torch
    import transformers
    import hanlp
    import flask
    print('所有依赖安装成功!')
} except Exception as e {
    print(f'安装验证失败: {e}')
}"

Write-Host "ok,HanLP server:" -ForegroundColor Cyan
Write-Host "python run_hanlp_server.py --host 0.0.0.0 --port 5000" -ForegroundColor White

# 保持PowerShell窗口打开
Write-Host "xxxxx..." -ForegroundColor Yellow
Read-Host 